package leetcode.code0959;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import leetcode.IDebug;
import leetcode.helper.H;

public class Solution implements IDebug {

	int m, n;

	Map<Integer, Integer> map;

	int cnt;

	public int regionsBySlashes(String[] grid) {
		map = new HashMap<>();
		cnt = 0;
		m = grid.length;
		n = grid[0].length();
		for (int i = 0; i < m; i++) {
			String str = grid[i];
			char[] line = str.toCharArray();
			for (int j = 0; j < n; j++) {
				char c = line[j];
				if (c == ' ') {// ' ' 0号
					int index = this.add(i, j, 0);// 第一次遇见，创建并查集头
					this.merge023(index, i - 1, j);// 向上合并023类，其实只有一种
					this.merge024(index, i, j - 1);// 向左合并024类
				} else if (c == '/') {// 1号/2号
					int index = this.add(i, j, 1);// 第一次遇见，创建并查集头
					this.merge023(index, i - 1, j);// 向上合并023类
					this.merge024(index, i, j - 1);// 向左合并024类
					this.add(i, j, 2);
				} else {// 3号\4号
					int index = this.add(i, j, 3);// 第一次遇见，创建并查集头
					this.merge024(index, i, j - 1);// 3号只能向左合并024类
					index = this.add(i, j, 4);// 第一次遇见，创建并查集头
					this.merge023(index, i - 1, j);// 4号向上合并023类
				}
			}
		}
		return cnt;
	}

	private int add(int i, int j, int k) {
		int index = this.index(i, j, k);// 头部代号
		map.put(index, index);// 添头
		cnt++;// 集合增加一个
		return index;
	}

	private void merge023(int index, int i, int j) {
		int idx = -1;
		if (map.containsKey(idx = this.index(i, j, 0)) || map.containsKey(idx = this.index(i, j, 2))
				|| map.containsKey(idx = this.index(i, j, 3)))
			this.merge(index, idx);
	}

	private void merge024(int index, int i, int j) {
		int idx = -1;
		if (map.containsKey(idx = this.index(i, j, 0)) || map.containsKey(idx = this.index(i, j, 2))
				|| map.containsKey(idx = this.index(i, j, 4)))
			this.merge(index, idx);
	}

	private void merge(int index1, int index2) {
		int p1 = this.parent(index1);
		int p2 = this.parent(index2);
		if (p1 != p2) {
			map.put(p1, p2);
			cnt--;// 合并后集合减少一个
		}
	}

	private int parent(int index) {
		if (index != map.get(index)) {
			map.put(index, this.parent(map.get(index)));
		}
		return map.get(index);
	}

	private int index(int i, int j, int k) {
		return i + j * n + k * m * n;
	}

	@Override
	public void debug4() {
		H.compare(4, this.regionsBySlashes(H.str2array2("[\"\\/\",\"/\\\"]")));
		H.compare(2, this.regionsBySlashes(H.str2array2("[\" /\",\"/ \"]")));
		H.compare(1, this.regionsBySlashes(H.str2array2("[\" /\",\"  \"]")));
		H.compare(5, this.regionsBySlashes(H.str2array2("[\"/\\\",\"\\/\"]")));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
